package com.ruoyi.web.controller.backstage;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;

import com.ruoyi.common.utils.file.SftpUtil;
import com.ruoyi.system.domain.IFileEntireInfo;
import com.ruoyi.system.service.IFileEntireInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.util.Date;

import static com.ruoyi.common.utils.DateUtils.systemDate;


/**
 * 系统服务
 * @author Administrator
 */
@RestController
@RequestMapping("/system/")
public class SystemController extends BaseController {


    /**
     * ip
     */
    @Value("${sftp.ftpIp}")
    private String ftpIp;
    /**
     *  端口
     */
    @Value("${sftp.port}")
    private Integer PORT;

    /**
     * 用户名
     */
    @Value("${sftp.username}")
    private String USERNAME;

    /**
     * 密码
     */
    @Value("${sftp.password}")
    private String PASSWORD;


    @Resource
    private IFileEntireInfoService fileInfoService;

    @GetMapping("/time")
    public AjaxResult time()
    {
        Date date = new Date();
        return AjaxResult.success("成功",date);
    }

    @RequestMapping(value = "/deleteFileByFileUrl", method = RequestMethod.POST)
    public AjaxResult deleteFileByFileUrl(@RequestBody String fileUrl){
        logger.info("删除文件入参：{}",fileUrl);
        try {
            IFileEntireInfo fileEntireInfo = fileInfoService.selectAsyncFileInfoByUrl(fileUrl);
            if (fileEntireInfo != null) {
                String location = fileEntireInfo.getLocation();
                String filePath = location.substring(0, location.lastIndexOf("/"));
                String fileName = location.substring(location.lastIndexOf("/")+1);
                SftpUtil sftpUtil = new SftpUtil(ftpIp, PORT, USERNAME, PASSWORD);
                sftpUtil.delete(filePath,fileName);
                fileInfoService.deleteAsyncFileInfoById(fileEntireInfo.getId());
                return AjaxResult.success();
            }else {
                logger.info("未找到此文件：{}",fileUrl);
                return AjaxResult.error();
            }
        } catch (Exception e) {
            logger.info("删除文件失败：{} , 原因：{}",fileUrl,e.getMessage());
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }
}
